<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>单选框全选反选等示例</title>
    <script type="text/javascript">
        window.onload = function () {
            var all = document.getElementsByName("all")[0];
            var items = document.getElementsByName("item");
            var reverse = document.getElementById("reverse");
            var submit = document.getElementById("sub");

            function myChooseFun(el, fun) {
                el.onclick = fun;
            }

            //全选或不全选按钮
            myChooseFun(all, function () {
                for (let i = 0; i < items.length; i++) {
                    items[i].checked = this.checked;
                }
            });
            //item选择，会影响到全选或不全选
            for (let i = 0; i < items.length; i++) {
                myChooseFun(items[i], function () {
                    let flag = true;
                    for (let j = 0; j < items.length; j++) {
                        if (!items[j].checked) {
                            all.checked = items[j].checked;
                            flag = false;
                        }
                    }
                    if (flag) all.checked =  flag;
                });
            }
            //反选,反选也要兼顾到全选或全不选
            myChooseFun(reverse,function () {
                let count = 0;
                for (let i = 0; i < items.length; i++) {
                    if (items[i].checked){
                        items[i].checked = false;
                    }
                    else{
                        items[i].checked = true;
                        count ++;
                    }
                }
                if (count !== items.length) all.checked = false;
                else all.checked = true;
            });
            //提交
            myChooseFun(submit,function () {
                let data = [];
                for (let i = 0; i < items.length; i++) {
                    if (items[i].checked) data.push(items[i].value);
                }
                let p = document.getElementById("p");
                let s = "";
                data.forEach(function (value,index,obj) {
                    s+=value+" ";
                });
                p.innerText = s;
            });

        }
    </script>
</head>
<body>
<div id="div1">
    爱好选择：<input type="checkbox" name="all" value=""/>全选/全不选
    <br>
    <input type="checkbox" name="item" value="lanQiu">篮球
    <input type="checkbox" name="item" value="z">足球
    <input type="checkbox" name="item" value="p">兵乓球
    <input type="checkbox" name="item" value="pq">排球
    <br>
    <input type="button" id="reverse" value="反选">
    <input type="button" id="sub" value="提交">
</div>
<div id="div2">
    <p id="p"></p>
</div>
</body>
</html>